# -*- coding:utf-8 -*-
# 通过调用kuboard，查看/更新镜像版本，调整容器数量

import json
from jsonpath import jsonpath
from flask import Flask, request, render_template, jsonify
import requests
import datetime
import time
import logging
import mylog
import sqlite3
from flask import abort
from concurrent.futures import ThreadPoolExecutor
import urllib3

app = Flask(__name__)
# 配置日志格式
time_tag = datetime.datetime.now().strftime("%Y-%m-%d")
log = mylog.Logger('all.log',level='error')
logger = log.logger
requests.adapters.DEFAULT_RETRIES = 5 # 增加requests重连次数
# 创建线程池执行器
executor = ThreadPoolExecutor(2)
# 存储进度数据
progress_data = {}
# 解决请求华为云时，出现 InsecureRequestWarning: Unverified HTTPS request is being made to host
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def get_conn():
    # 定义该函数用来连接数据库
    return sqlite3.connect('updatehistory.db')

# 创建数据库
def open_db(conn=None):
    if conn:
        print("Opened database successfully")
    else:
        print("Open database fail")
        return False
    # 更新记录
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS UpdateHistory
           (ID  INTEGER PRIMARY KEY  NOT NULL,
           UUID            TEXT      ,
           UpdateImage     TEXT      NOT NULL,
           BeforImage      TEXT      NOT NULL,
           Environment     TEXT      NOT NULL,
           EnvUrl          TEXT      NOT NULL,           
           ImageBranch     CHAR(30)  ,
           UpdataRes       CHAR(25)  ,
           UpdateDate      CHAR(25)  NOT NULL);''')
    # print("Table created successfully")
    conn.commit()
    conn.close()
    return True


# 不同环境的配置信息
def get_env_info(env=None):
    # 获取环境配置信息
    # 不同的环境，地址，token信息不同
    if not env:
        return None
    env_info = {}
    hk_uat_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6Iml3QUsydWgyUGpHNFpFNENoLUdZeGxtREJnUDBzeDhtd3MxR1ZqUHpVTk0ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOTk4MGM3ZTgtY2Y4My00ZTM1LTg4NjYtZTM2NjM2MDMwYTRmIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.Z8vaNXGh-_H8k2Pllg9PKOEHsICemcmvxQWcKx0JXteAKBbXajz8AfmJgDxLLe0uLtVAChv7GnIZbyMjrBF4R3L_-G2QlAC-wNb1BWEYkglItt-JRRx_olPfpA3CKEUW23TwH08WK-X1sg4nYvMIyxe8OY4Ow7e6SdDuF3Zobxoz7AgOPUcG9QQhu6SAh6YwWGkyaiA9l1KnonT74Mdgbxv28oThPaebwOEL8cc9uPkHzTMSTgP1hMq0lFToYgn4UCMiBmYZCo2M1rY6tc6c6qVLUNLjeCKWg8EqP9UhQeUCF1i1vvIHqXhgO6PEMmR3dC_mMn-0X4q66F2AwmsKkw"
    if env == 'sim':
        env_info['env_name'] = "演示环境"
        env_info['basurl'] =  r"https://hwkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/sim/deployments"
        env_info['token'] = hk_uat_token
    if env == 'uat':
        env_info['env_name'] = "通用测试环境"
        env_info['basurl'] =  r"https://hwkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        env_info['token'] =  hk_uat_token
    if env == 'dev':
        env_info['env_name'] = "开发环境"
        env_info['basurl'] =  r"https://hwkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/dev/deployments"
        env_info['token'] =  hk_uat_token
    if env == 'dev2':
        env_info['env_name'] = "开发环境2"
        env_info['basurl'] =  r"https://hwkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/dev2/deployments"
        env_info['token'] =  hk_uat_token
    if env == 'pre':
        env_info['env_name'] = "预发环境"
        env_info['basurl'] =  r"https://hwkuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/pre/deployments"
        env_info['token'] =  hk_uat_token
    if env == 'prod':
        env_info['env_name'] = "通用正式环境"
        env_info['basurl'] = r"https://kuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/zj/deployments"
        env_info['token'] = "eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tcWtwZmIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjMwZDY4MTFlLTdhN2QtMTFlYy1iNTkyLTAwMTYzZTA2MzdhMiIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmhrLWRldnVzZXIifQ.EykQn4-fdmcgwoF3uGYVYsgLuqLE67hpTnk6OAGbJtECYW3tpJCmocPac8_HIVJqrXlbcyu-1Qgq_CS27dcg6v0lDDetTUTKLFMRUu6FD3VF4dmNx8doicwvWrb3_T1RdHN6OpzpTy-cTe_g-2-3Ub69HizZAqpUQeuHTypDV-mT72X-ydpo_PhwwBb814yic6bAjL5WkkNXaulEwobLw0FaUtn3n29OGrDZJaJkH450X2ccSwELb8QWK-1wZ3blzixEAvFVaYrHD6-OuC5FIjfQk_Nb1oCTwsDaGwMW5yICDwsuOZq0XII8LYdAtXQRqzZwUJmrAslKUdYyVHh75A"
    if env == 'zljuat':
        env_info['env_name'] = "足力健测试环境"
        env_info['basurl'] =  r"https://kuboard.zljllcy.com/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRlQjctZ2V2Z0ZjN0ZmQ3BMYlJoTWg2MWxWZ3ZxWFZjSnI5ODhLRTRkZEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1rOXA1ZyIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWUxZmRhZWUtMTM2NS00MWJjLTllM2YtNTA2MGNlMDhhN2IyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.cuT2uBo94PbI1gdcxZ6YJMS6f6aw9ZQxAzK18hl_e8M7btBDiAdTQcj1EjkPSQIQzl2BR_3od5onYacjzWAW6cxIncQc2bWyq-k1TIh4RSc9l9zwGVsJ6uPMO7Z0MZcWn1xqgVLtQp_uQg5YXAsaAaUvk6kHuTkPbEKsHcpHeTjguxwnWQNKWGMCxBaIyKuUV6s5AEQQu7-0igWbzoFvm650KCa14yOj1yXAuXXByxPBmZ__YQshWDRAAn6lzhoPhkrh5RmIFkAyIW6F09u7IbCwA4PNK1RtxXjY_tjokYm7gYlWmK1JbBh3LPjLRvVhbQC64mX__Cv1VT1NIeDmeg"
    if env == 'zljprod':
        env_info['env_name'] = "足力健正式环境"
        env_info['basurl'] =  r"https://kuboard.zljllcy.com/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRlQjctZ2V2Z0ZjN0ZmQ3BMYlJoTWg2MWxWZ3ZxWFZjSnI5ODhLRTRkZEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1rOXA1ZyIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWUxZmRhZWUtMTM2NS00MWJjLTllM2YtNTA2MGNlMDhhN2IyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.cuT2uBo94PbI1gdcxZ6YJMS6f6aw9ZQxAzK18hl_e8M7btBDiAdTQcj1EjkPSQIQzl2BR_3od5onYacjzWAW6cxIncQc2bWyq-k1TIh4RSc9l9zwGVsJ6uPMO7Z0MZcWn1xqgVLtQp_uQg5YXAsaAaUvk6kHuTkPbEKsHcpHeTjguxwnWQNKWGMCxBaIyKuUV6s5AEQQu7-0igWbzoFvm650KCa14yOj1yXAuXXByxPBmZ__YQshWDRAAn6lzhoPhkrh5RmIFkAyIW6F09u7IbCwA4PNK1RtxXjY_tjokYm7gYlWmK1JbBh3LPjLRvVhbQC64mX__Cv1VT1NIeDmeg"
    if env == 'psuat':
        env_info['env_name'] = "宝胜测试环境"
        env_info['basurl'] =  r"http://pskuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6Im1wMmNyVDNqMmg4ZDlLNjA3YTNNcGpwMkpWMTMzUTR1akFRbmlic1VkS0EifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1mbmRzNSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOWI1ZGMzZGMtOWJiYy00Y2I5LWE4MTAtNGI4NGZjYzJkYTdmIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.dOBRbjGUCDty9npLZEfJHG653zQouOimTWye0pc7onv3w0sEICPoTPYX2stYrNrhL_dQZzii6pIs8Erd66bL7F-3m-Y-0a9NjXqYlSQgXJVpvx4hAMxaTOeOohv4YpvYOQcdTPPU3dYAsAyhNQ_XUe8rDfmyp1qQNAiXEhg10C6j5Oq5XVP5z4tNqb8zhP2029T1a0X0c9Jl-jnO2c5x60RhwZn23e5ci2vHHIB4Z02dWVul89Wa0bsmf0TXAmmMgBrfs2l5Ts1E77fbXlva0nG8jh7q6z2Es1DKHMvSdF6ou5pTBjfRRQX8scuNRwOso43b5dPFUribTTTwEr4WIg"
    if env == 'psprod':
        env_info['env_name'] = "宝胜正式库环境"
        env_info['basurl'] = r"https://pskuboard.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] = "eyJhbGciOiJSUzI1NiIsImtpZCI6Im1wMmNyVDNqMmg4ZDlLNjA3YTNNcGpwMkpWMTMzUTR1akFRbmlic1VkS0EifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi1mbmRzNSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOWI1ZGMzZGMtOWJiYy00Y2I5LWE4MTAtNGI4NGZjYzJkYTdmIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.dOBRbjGUCDty9npLZEfJHG653zQouOimTWye0pc7onv3w0sEICPoTPYX2stYrNrhL_dQZzii6pIs8Erd66bL7F-3m-Y-0a9NjXqYlSQgXJVpvx4hAMxaTOeOohv4YpvYOQcdTPPU3dYAsAyhNQ_XUe8rDfmyp1qQNAiXEhg10C6j5Oq5XVP5z4tNqb8zhP2029T1a0X0c9Jl-jnO2c5x60RhwZn23e5ci2vHHIB4Z02dWVul89Wa0bsmf0TXAmmMgBrfs2l5Ts1E77fbXlva0nG8jh7q6z2Es1DKHMvSdF6ou5pTBjfRRQX8scuNRwOso43b5dPFUribTTTwEr4WIg"
    if env == 'jmwuat':
        env_info['env_name'] = "九牧王测试环境"
        env_info['basurl'] =  r"https://kuboard.joeone.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6Im5OaTR2a3p0YkoxQjhqdGdQSWlJaGhnblpXZzdXX0pEUk9RNDV3V0U1dUUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbi03czRkNiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiMWM0MmM0NjMtNTM2MC00ZDBjLWI4NzEtYjFkZmY4NDUyNjFkIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.GS_4XTQajW0IAblazR1sV3LKyWK9afdbDOSX7A9UNk1r6w_KQ_IAnaziZVVNTPOhU-rnsaSR-xmcVvoqLlDHfh2rkwpDU5nsc68n8gWPQYpVy7kH5EYmxpTPPjx7xtHHhPfTin8ilibAb072tMMjmd3RPdQJutthqFDx2OQx1NAZDA2s1PYT4lKXW-dR9zspw8bKeBPoW-zidCsKXGeTsX6H55oxAc1WlGYm0v7qQatzIHzbo6hM2fIgP83LGh5l-RJv5Ik6KXtCEp921a5E9xG2Dpys-O0ONpnQAdEsBCSG1lOoHwam008bDvvpAoSMFJEE2JQzcKalVyiqRnqygw"
    if env == 'jmwprod':
        env_info['env_name'] = "九牧王正式环境"
        env_info['basurl'] =  r"https://tkuboard.joeone.net/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IjAxZFM1S3RmRzJWUlBzeHA2SHZObWgzVjNoaDFUeFJueVo0ejFQR1BSOU0ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJwcm9kIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tYnA1bTkiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImVmMmExZTZlLTY4OTgtNGI2MC05OGNkLWViYWYzNzNjY2MxYiIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpwcm9kOmhrLWRldnVzZXIifQ.nHQJ2T8J_hmBqd2bGTM-edPuYpGWIoSE_aghpU38S6EjRltxNQyJkOWtt55otLjpvR-QiT27dxi7h486qlgKT3RX-_9Fajp7rEpW98K3mrdDiaiKMHP9DAKGCr-xgscaIVa5gT_6NIS9tK3hE5n7fn-4W9ki48bES4y-1ZiQ-9XTP2YQYfDSW9ZAMcHSnFrgFAl_mKimhHMbrNzPYJ7N7BRNgdJOlOaybU83DAt60sWFQlcQqUnAwxNunB6z3B4mGZm8TWWt09HKWwlfJJR9A56NiW02xXf_tfG4QD5M_pird_Oz2rkUuRBKMwF8KcR7jeOnCPU3qYJO2fv3uqdMQg"
    if env == 'lsprod':
        env_info['env_name'] = "联晟正式环境"
        env_info['basurl'] =  r"https://kuboard.missonep.com/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IlRHcjNLbzFHMHBpLVRVWDVzdUdIV2UtQWlZUFcxSXRfcjVwVzhJamp6QkEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJwcm9kIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tYnFreDUiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjFhOTI5ZDJkLWM2NmItNDI4NC05OWI1LWNjMTViYzgxMmU1NyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpwcm9kOmhrLWRldnVzZXIifQ.IP1Alw5lmXsIkpyS9Km5IZH8FK_7aYhSMVjixH6zx4G9huTGyIKjyj0Ep-ew-YHepL5CNrXh3QPFDHb2GLnNi18M6MK7chYMg4UTAy5NLawLn_dy8WXuT_H35NH_1UQvKraxIJGa9pn5FhzHALCVXGFaF3wrNhb1ehCIPPfLGqOzVUZXZ80s5SEi8zRhiaeR_WhF3tlZLWMP34pUiPtlVVnQwTiSoJvxNlNFUrxonRyD7vi3__m5k2C2DS3nVo3_zgo9QmcNt--AD_ac1Q4Jj-zLTSu5p_Z6s1KNletRpArSjEIAcg3Si67K3GHyqATdEwkngxuFQhcsagMLUZD56w"
    if env == 'hwprod':
        env_info['env_name'] = "华为云正式环境"
        env_info['basurl'] =  r"https://hwk.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IlJYVHg0czJacVdpNDhjWjR0czNPNERoRV9EVFBsYXFWMU9CeENEX2dtWEUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJrdWJvYXJkLXVzZXItdG9rZW4tdG5tZjQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoia3Vib2FyZC11c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiODRlODIzN2EtZjFlMS00Njc2LThjZjUtNjZjOTBlZjRiOGY2Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50Omt1YmUtc3lzdGVtOmt1Ym9hcmQtdXNlciJ9.oSJPfhSlLx1WInIxRQtKNLvhxS3EGwxszDISV-lo2MScoYo6G0JHp77dQtZeandzfiMP-8p1looccxGq20UiXEQUgGfo029GPjrAP2Jd38bCvpiF5bsX19-fVC3-FeEhLKg536R7Od2XGAip0zkkuG7h9LpPmvLyC2WMmYs4wwCU2om2GxwBTyBCNJ-gMUrb0nH2rgHM4v6RWEuSWQlO2tihzgL3JzCXo_6CrgAJREl6cTfjJrPG92vlgWSetUcBy1i-hYGp4-8PdotrpLaBols7vaWcZS5gX4Oi_GoQIH9tGh1gtaORgLsmOttfcPOg_sg4jnfOKH36BjU_7T-GZw"
    if env == 'caprod':
        env_info['env_name'] = "C&A正式环境"
        env_info['basurl'] =  r"https://kuboard.win-eco.com/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IjVxS1BOQmxyUTRacC1JLXdMYVRYb2VDN3ZXUWtmUDJVOW1UTHRpREYxSEEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJwcm9kIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tZHg4Y2giLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjlhYjRjMjllLTFjNTctNGIzMi1hNTQ4LWFmZDI4MzAxOTBlNSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpwcm9kOmhrLWRldnVzZXIifQ.ruSpke6xtexfjC2AmRcYYJDSFKEEeZui-5FX4j0xwBHDfTU9D8Scach_V_VzlmBl_DjetKN2VNmN-VfCRhhTohFU-LMExNh-nQILDyAC2bHKYtWHNVFF8J4MaLzVJs-cZ9GUQRKwrOXoKM2HmhNvpFtYPs1-XehDMAE15SpK-i9v1h2ORpwSmObbuJl-Hkl0_pKPJd2PI8cHvaPuVcU1B8u26CE9fBjJMY7b-eQ87xdmUl-WUEjR6_tFavXH4PdEJAj7o9O4GAhk-vtZXeggtsz78fgdEfNcFXxM1RrwmooiK2JA5yINlopsRMJI1UUf1pLxqTj9VbVFiZLBDmG_mw"
    if env == 'ctuat':
        env_info['env_name'] = "创托测试环境"
        env_info['basurl'] =  r"http://kuboard.yysjls.com/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IkJ5dFUzNUtYdVhybXgtLXZxRGV5bzdlQVdvRWJZUW5JOFhzNHJGdVF3RHMifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tZ2ZsNXAiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImEwNzRhZTY0LTIyMzAtNDEzNC1iODIzLWVhMjU4NTA3NDJhMyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmhrLWRldnVzZXIifQ.dgTnEWsjAPaef1Z4VLIottVO3FKVwIRjynm5AGF8o42Lch7mbEL-5H_k9P2uxyzfpVrxT0HTbINSelx3ZAv014HYrNY4zNNuVh23nf86Q_ZB8-MuEhiYuIuWzZ4plVXN0M7wq0RZq-Wk7AQFfq2lE7pttBPD8QGYmPZc_EFumdLpuGZRuAkOzpVLvEh5_mdIHGrrBHMBWB_nfhw5AMl57rIIfNZ4m8SiVrpkI6csH6a4CgBtW1gzgJxEOMFpOo_7pYd3Y9QgaoGRynsi0kAPavAhUtGsE5a8u0bD3L3R3jLoUPgb2BoiinSOr9b366VNW7-VLPMvPn-D0BFi7een_w"
    if env == 'ctprod':
        env_info['env_name'] = "创托正式环境"
        env_info['basurl'] =  r"http://kuboard.yysjls.com/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6IkJ5dFUzNUtYdVhybXgtLXZxRGV5bzdlQVdvRWJZUW5JOFhzNHJGdVF3RHMifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImhrLWRldnVzZXItdG9rZW4tZ2ZsNXAiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiaGstZGV2dXNlciIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6ImEwNzRhZTY0LTIyMzAtNDEzNC1iODIzLWVhMjU4NTA3NDJhMyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmhrLWRldnVzZXIifQ.dgTnEWsjAPaef1Z4VLIottVO3FKVwIRjynm5AGF8o42Lch7mbEL-5H_k9P2uxyzfpVrxT0HTbINSelx3ZAv014HYrNY4zNNuVh23nf86Q_ZB8-MuEhiYuIuWzZ4plVXN0M7wq0RZq-Wk7AQFfq2lE7pttBPD8QGYmPZc_EFumdLpuGZRuAkOzpVLvEh5_mdIHGrrBHMBWB_nfhw5AMl57rIIfNZ4m8SiVrpkI6csH6a4CgBtW1gzgJxEOMFpOo_7pYd3Y9QgaoGRynsi0kAPavAhUtGsE5a8u0bD3L3R3jLoUPgb2BoiinSOr9b366VNW7-VLPMvPn-D0BFi7een_w"
    if env == 'gcpuat':
        env_info['env_name'] = "GCP测试环境"
        env_info['basurl'] =  r"http://gcpk.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/uat/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6InRVdjVGTFdYU0thRXhGNjNYS0RVNW9ZNnRCZVFvcnBOZno4MFY4WjRaSU0ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNzVhNzc3ZTAtM2NkNi00Njg5LWI0M2YtM2FhZGU3ZTE3ZWYyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.jzoOP-0OSFerjLjeRkaxgSktMsCNPChT0aQP1M60Me_IV4jDFn0vOec5qvqs1i7vUt3Upab8qDsz9iwtbw6fjpHoFCsNavZ4zLP7MHhM8eewwIcdy-8wMzqVzUgWjNIuw99ORfFws6f2TmcBPAp7iu0v2ejkdsbG0q1s5MQFdz5okODKsFteVSWRySFeoZs2guvRMXBzyfEhRj4RNK3vYLa6CsD5FJfpgBwDAB6rPecwaN2E3qbJZi3myYqPM2GjlzBtIdA_SSEcTNbmRPV0DGWS_tNQ1gy0-J-NOMgjWkhIAUhcmIu40pjZVOb7W_I_0jbBXXe2WiPNtwdtehgXNA"
    if env == 'gcpprod':
        env_info['env_name'] = "GCP正式环境"
        env_info['basurl'] =  r"http://gcpk.hkitcloud.net/k8s-api/apis/apps/v1/namespaces/prod/deployments"
        env_info['token'] =  "eyJhbGciOiJSUzI1NiIsImtpZCI6InRVdjVGTFdYU0thRXhGNjNYS0RVNW9ZNnRCZVFvcnBOZno4MFY4WjRaSU0ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJ1YXQiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiaGstZGV2dXNlci10b2tlbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJoay1kZXZ1c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNzVhNzc3ZTAtM2NkNi00Njg5LWI0M2YtM2FhZGU3ZTE3ZWYyIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OnVhdDpoay1kZXZ1c2VyIn0.jzoOP-0OSFerjLjeRkaxgSktMsCNPChT0aQP1M60Me_IV4jDFn0vOec5qvqs1i7vUt3Upab8qDsz9iwtbw6fjpHoFCsNavZ4zLP7MHhM8eewwIcdy-8wMzqVzUgWjNIuw99ORfFws6f2TmcBPAp7iu0v2ejkdsbG0q1s5MQFdz5okODKsFteVSWRySFeoZs2guvRMXBzyfEhRj4RNK3vYLa6CsD5FJfpgBwDAB6rPecwaN2E3qbJZi3myYqPM2GjlzBtIdA_SSEcTNbmRPV0DGWS_tNQ1gy0-J-NOMgjWkhIAUhcmIu40pjZVOb7W_I_0jbBXXe2WiPNtwdtehgXNA"


    return env_info

# 根据返回页面，获取镜像信息（名称、路径）
def image_info_extract(response_str):
    """
    提取镜像信息
    传入：k8s返回的json字符串
    返回：镜像名称字典，格式：{'镜像名称':{'space': '空间名称', ...}，
    如：{'backjob': {'space': 'uat-backjob', 'image': '202201140201-backjob', 'image_url': 'hkacr-registry-vpc.cn-shenzhen.cr.aliyuncs.com/hk_docker/backjob'},
    """
    env_imags_info = {}
    cnt = len(jsonpath(response_str.json(), "$.items[*].metadata.name"))
    for i in range(cnt):
        try:
            replica = "$.items[" + str(i) + "].spec.replicas" # 副本数量
            replica_cnt = jsonpath(response_str.json(), replica)[0]
            # 副本数量为0，认为该副本已经停用
            if int(replica_cnt) > 0:
                image_xpath = "$.items[" + str(i) + "].spec.template.spec.containers[0].image"
                space_name = "$.items[" + str(i) + "].spec.template.spec.containers[0].name"
                tmp = jsonpath(response_str.json(), image_xpath)[0]
                # 镜像版本
                # 镜像中可能出现多个冒号，类似这种【hub.hengkangit.com:6337/hk_docker/guiderapp:202003150250-guiderapp】
                tmp_list = tmp.split(":")
                if len(tmp_list) > 2:
                    image_name_url = ":".join(tmp_list[0:-1])
                else:
                    image_name_url = tmp_list[0]
                image_name = tmp_list[-1]
                # 镜像仓库名称
                # 要做长度判断，避免出现有些仓库部署的名称不规范
                image_tag = image_name.split("-")[1]
                # print(image_name)
                image_space = jsonpath(response_str.json(), space_name)[0]
                # 形成镜像信息字典
                # 当部署的环境中，有多个命名空间，可能存在有docker名称重复，但是运行着不同的版本的情况。要对镜像标签做检查，防止多个同名镜像标签覆盖
                if image_tag not in env_imags_info.keys():
                    env_imags_info[image_tag] = {"space": image_space, "image": image_name, "image_url": image_name_url}
                else:
                    tmp_tag = image_tag + "-1"
                    env_imags_info[tmp_tag] = {"space": image_space, "image": image_name, "image_url": image_name_url}
                    # env_imags_info['err'] = {"info": "存在同名但不同版本的镜像docker", image_tag}
        except Exception as bug:
            print("Have a bug:", bug)

    # logger.debug(env_imags_info)
    # print("在镜像信息获取函数中：")
    # print(env_imags_info)
    return env_imags_info

def get_image_diff_info(env_s, env_t, cmptype, based_right):
    """
    获取镜像版本对比信息。

    """
    # 获取环境连接信息
    tmp_env_s = get_env_info(env_s)
    url_s = tmp_env_s['basurl']
    token_s = tmp_env_s['token']
    env_str_s = tmp_env_s['env_name']
    tmp_env_t = get_env_info(env_t)
    # print("目标环境信息：", env_t)
    url_t = tmp_env_t['basurl']
    token_t = tmp_env_t['token']
    env_str_t = tmp_env_t['env_name']
    s = requests.session()
    s.keep_alive = False  # 关闭多余连接
    # 请求报头
    headers_s = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
        'Authorization': "Bearer " + token_s,
        'Content-Type': 'application/json-patch+json'
    }
    headers_t = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
        'Authorization': "Bearer " + token_t,
        'Content-Type': 'application/json-patch+json'
    }
    try:
        print("开始请求镜像信息")
        response_s = s.get(url_s, headers=headers_s, verify=False)  # verify=False，解决SSL 根证书验错误
        response_t = s.get(url_t, headers=headers_t, verify=False)  # verify=False，解决SSL 根证书验错误
        # print(response_s.text)
    except Exception as BUG:
        print("Have a bug:", BUG, "\n")
        logger.info("链接K8S失败")
        print("链接地址失败:", url_s)
        print("链接地址失败:", url_t)
        print(response_s, response_s.status_code)
        print(response_t, response_t.status_code)
        print("链接K8S失败")
        return_dict['return_info'] = "连接K8S失败，请稍后重试"
        return json.dumps(return_dict, ensure_ascii=True)
    # logger.debug(response_t.text)
    # print(response_t.text)
    print("开始分析镜像信息")
    image_s = image_info_extract(response_s)
    image_t = image_info_extract(response_t)
    tmp_s = []
    tmp_t = []
    for k in image_s: tmp_s.append(image_s[k]['image'])
    for k in image_t: tmp_t.append(image_t[k]['image'])
    print("image_s:", tmp_s)
    print("image_t:", tmp_t)
    # 提取新的镜像
    # 遍历最长的字典
    for k in list(image_s.keys() if len(image_s.keys()) > len(image_t.keys()) else image_t.keys()):
        try:
            if image_s[k]['image'] == image_t[k]['image']:
                image_s.pop(k)
                image_t.pop(k)
            else:
                if int(based_right) == 0:
                    # 没有选择以右边为准，只保留新的镜像
                    image_s.pop(k) if image_s[k]['image'] < image_t[k]['image'] else image_t.pop(k)
                else:
                    # 以右边为准，删除左边
                    image_s.pop(k)

        except KeyError:
            if k in image_s:
                msg_str = str(env_t) + "环境" + "没有" + str(k) + "镜像"
            else:
                msg_str = str(env_s) + "环境" + "没有" + str(k) + "镜像"
            print("---->", cmptype)
            if int(cmptype) == 1:
                # 只保留非独有镜像
                if k in image_s:
                    image_s.pop(k)
                    print("只保留非独有镜像，剔除：", k)
                else:
                    image_t.pop(k)
                    print("只保留非独有镜像，剔除：", k)
            logger.info(msg_str)

    # 把镜像名称封装成字典
    image_dict = {}
    tmp_s = ""
    tmp_t = ""
    for k in image_s.values(): tmp_s += k['image'] + ','
    for k in image_t.values(): tmp_t += k['image'] + ','
    image_dict[env_str_s] = tmp_s[0:-1]
    image_dict[env_str_t] = tmp_t[0:-1]
    print("这里是个测试用-1：", image_dict)
    return image_dict


def check_update_status(uuid, url_list, header):
    """
    通过返回的报文判断是否已经更新成功
    :param response_str:
    :return:
    """
    logger.debug("in check_update_status")
    # 用于执行超时计算
    start_time = datetime.now()
    cnt = 0
    while True:
        cnt += 1
        print("in check_update_status:", cnt)
        # 大于120秒，超时，当作失败
        if (datetime.now() - start_time).seconds > 120:
            progress_data[uuid] = "更新超时"
            return False
        tmp_url = url_list
        if not tmp_url:
            # 全部镜像都更新成功后，退出
            break
        for basurl in tmp_url:
            try:
                response = requests.get(basurl, headers=header, verify=False)
            except:
                logger.debug("检查更新状态--链接K8S失败")
                continue
            # 取不到数据会返回false
            status = jsonpath(response.json(), "$.status.unavailableReplicas")
            print(response)
            if status:
                print('在更新中:', basurl)
            else:
                print("更新完成:", basurl)
                url_list.remove(basurl)
    return True


# 更新镜像版本
# @app.route("/updateimage/<uuid>", methods=["GET", "POST"], strict_slashes=False)
# def updateimage(uuid):
@app.route("/updateimage/", methods=["GET", "POST"], strict_slashes=False)
def updateimage():
    """
    通过uuid将数据存入变量progress_data
    """
    uuid = "123456"
    logger.debug("In updateimage")
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': 'success', 'result': True}
    # 获取传入的参数 post
    if request.method == "POST":
        data_str = request.form.to_dict()
    qurey_data = data_str['imageName']
    env = data_str['env']
    # 判断入参是否为空
    if (qurey_data is None) or (env is None):
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = '必填请求参数不能为空'
        return_dict['result'] = 'False'
        logger.debug("有必填参数为空")
        return json.dumps(return_dict, ensure_ascii=False)
    env_info = {}
    env_info = get_env_info(env)
    if not env_info:
        return_dict['return_code'] = '500'
        return_dict['return_info'] = '获取kuboard配置信息失败'
        return_dict['result'] = 'False'
        logger.debug("获取配置信息失败，可能无法链接导致")
        abort(500)
        return json.dumps(return_dict, ensure_ascii=False)
    token = env_info['token']
    basurl = env_info['basurl']
    env_name = env_info['env_name']
    # 请求报头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36',
        'Authorization': "Bearer " + token,
        'Content-Type': 'application/json-patch+json'
    }
    try:
        response = requests.get(basurl, headers=headers, verify=False)
        # print(response.text)
    except:
        logger.debug("链接K8S失败")
        abort(500)

    # logger.debug(response)

    progress_data[uuid] = "上传镜像成功"

    # 提取镜像信息
    print("准备提取镜像信息")
    env_imags_info = {}
    cnt = len(jsonpath(response.json(), "$.items[*].metadata.name"))
    # print("发现镜像数量：", cnt)
    if cnt < 1:
        print("无法提取到对应环境的镜像信息")
        abort(500)
    for i in range(cnt):
        try:
            image_xpath = "$.items[" + str(i) + "].spec.template.spec.containers[0].image"
            space_name = "$.items[" + str(i) + "].spec.template.spec.containers[0].name"
            # space_name = "$.items[" + str(i) + "].metadata.labels.release"
            tmp = jsonpath(response.json(), image_xpath)[0]
            # 镜像版本
            tmp_list = tmp.split(":")
            if len(tmp_list) > 2:
                image_name_url = tmp_list[0] + tmp_list[1]
                image_name = tmp_list[2]
            elif len(tmp_list) > 0:
                image_name_url = tmp_list[0]
                image_name = tmp_list[1]
            else:
                print(tmp_list)
                image_name_url = ""
                image_name = tmp_list[0]
        except Exception as e:
            print("分离客户环境镜像版本失败，报错信息：", e)
            continue
        try:
            # 镜像仓库名称
            image_tag = image_name.split("-")[1]
            image_space = jsonpath(response.json(), space_name)[0]
            # 形成镜像信息字典
            env_imags_info[image_tag] = {"space": image_space, "image": image_name, "image_url": image_name_url}
        except Exception as e:
            print("提取镜像名称失败，镜像内容：", image_name)
            print("异常信息：", e)
            continue
        # print(image_name_url)
        # print(image_space)
        # print(image_tag)
    # print(env_imags_info)

    progress_data[uuid] = "开始更新镜像"
    logger.debug("准备更新镜像")
    # update_success = 0
    update_fail_image = []
    image_cnt = 0
    conn = get_conn()
    cur = conn.cursor()
    # 更新镜像
    for image in qurey_data.split("\n"):
        image = image.strip()
        if not image: # 跳过空行
            continue
        input_tag = image.split("-")[1]
        image_cnt +=1
        local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        # 更新的空间命名（docker部署空间）
        update_space = env_imags_info[input_tag]["space"] # 这个方式有问题，真正的路径可能不是space的名称
        # 更新报文里面的镜像要包含对应的镜像路径
        update_image = env_imags_info[input_tag]["image_url"] + ":" + image
        # 接口路径，具体到镜像
        update_url = basurl + "/" + update_space
        # 记录上传成功的镜像路径，用于后面检测镜像是否更新完成
        update_url_for_check_list = []
        update_data = [{"op": "replace", "path": "/spec/template/spec/containers/0/image", "value": update_image}]
        sqlstr = "INSERT INTO UpdateHistory (ID,UUID,UpdateImage,BeforImage,Environment,EnvUrl,ImageBranch,UpdataRes,UpdateDate) \
                  VALUES (?,?,?,?,?,?,?,?,?)"

        # 相同镜像不更新
        if image.lower() == env_imags_info[input_tag]["image"]:
            logger.info("服务器已经是这个镜像版本：" + image)
            cur.execute(sqlstr,(None, "", image, "", env_name, update_url,"", "更新的镜像与运行中的镜像相同", local_time))
        else:
            try:
                requests.packages.urllib3.disable_warnings()
                response = requests.patch(update_url, json=update_data ,headers=headers, verify=False)

                if response.status_code == 200:
                    update_url_for_check_list.append(update_url)
                    logger.info("更新成功")
                    logger.info(env_imags_info[input_tag]["image"] + ' --> ' + image)
                    logger.info(env_name + "镜像更新成功：" + env_imags_info[input_tag]["image"] + ' --> ' + image)
                    cur.execute(sqlstr, (None, "", image, env_imags_info[input_tag]["image"], env_name, update_url, "",\
                                         "更新成功", local_time))
                elif response.status_code == 404:
                    logger.info("更新失败，镜像路径访问失败:", update_url)
                    cur.execute(sqlstr, (None, "", image, env_imags_info[input_tag]["image"], env_name, update_url, "", \
                                         "更新失败，镜像路径访问失败", local_time))
                else:
                    logger.info("更新失败" + image)
                    logger.debug(response.text)
                    update_fail_image.append(image)
                    cur.execute(sqlstr, (None, "", image, env_imags_info[input_tag]["image"], env_name, update_url, "", \
                                         "更新失败", local_time))
            except:
                pass

    # 在多线程任务里面去检查更新的状况
    # executor.submit(check_update_status, uuid, update_url_for_check_list, headers)
    if update_fail_image:
        return_dict['return_code'] = '500'
        return_dict['return_info'] = '存在更新失败的镜像:' + "\n".join(update_fail_image)
        return_dict['result'] = 'False'
        conn.commit()
        conn.close()
        abort(500)  # 返回500报错给前端
    conn.commit()
    conn.close()
    # time.sleep(5)
    return json.dumps(return_dict, ensure_ascii=True)


@app.route('/show_progress/<uuid>')
def show_progress(uuid):
    '''
    前端请求进度的函数
    '''
    return jsonify({'res': progress_data[uuid]})



# 环境版本差异对比
@app.route("/imagediff_info", methods=["GET", "POST"], strict_slashes=False)
def image_diff_info():
    logger.debug("In imagediff_info")
    print("In imagediff_info")
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': 'success', 'result': True}
    # 获取传入的参数 post
    if request.method == "POST":
        data = request.form.to_dict()

    env_s = data['env_s']
    env_t = data['env_t']
    if not env_s or not env_t:
        return_dict['return_info'] = "无法对比，传入的对比环境为空"
        return json.dumps(return_dict, ensure_ascii=True)
    # 对比类型（是否只对比两边都存在的镜像）
    cmptype = 0
    cmptype = data['cmptype']
    based_right = 0
    based_right = data['based_right']
    image_dict = {}
    image_dict = get_image_diff_info(env_s, env_t, cmptype, based_right)
    return_dict['return_info'] = image_dict
    print(return_dict)
    return json.dumps(return_dict, ensure_ascii=True)

@app.route("/getdbinfo", methods=["GET", "POST"], strict_slashes=False)
def get_db_range():
    print("In get_db_range")
    # 默认返回内容
    return_dict = {'return_code': '200', 'return_info': 'success', 'result': True}
    # 获取传入的参数 post
    if request.method == "POST":
        data = request.form.to_dict()

    env_s = data['env_s']
    env_t = data['env_t']
    if not env_s or not env_t:
        return_dict['return_info'] = "无法对比，传入的对比环境为空"
        return json.dumps(return_dict, ensure_ascii=True)
    # 对比类型（是否只对比两边都存在的镜像）
    cmptype = 0
    based_right = 0
    image_dict = get_image_diff_info(env_s, env_t, cmptype, based_right)
    tmp_env_t = get_env_info(env_t)
    env_str_t = tmp_env_t['env_name']
    # 定义程序和数据库的对应关系
    db_name = {}
    
    for image_name in image_dict[env_str_t]:
        tmp_name = image_name.split("-")
        if len(tmp_name) > 1:
            pass
        else:
            pass

    # return_dict['return_info'] = image_dict
    # print(return_dict)
    # return json.dumps(return_dict, ensure_ascii=True)


# 首页
@app.route("/", methods=["GET"])
def index():
    return render_template('index.html')

# 获取数据库范围
@app.route("/db", methods=["GET"])
def DB_range():
    return render_template('getDBRange.html')

# 环境版本
@app.route("/imagediff", methods=["GET"])
def imagediff():
    return render_template('difImage.html')


if __name__ == "__main__":
    # 更新记录存储到数据库中
    conn = get_conn()
    if open_db(conn):
        app.run(host = "0.0.0.0",port=5002,debug=True)
    else:
        print("I have a err to exit.")
        exit(-1)
